<template>
  <div class="home-container">
    <SideMenu />
    <div class="main-content">
      <div class="content-layout">
        <!-- Left Column -->
        <div class="left-column">
          <!-- Assistant Info Section -->
          <div class="assistant-info-section">
            <el-form
              ref="formRef"
              :model="virtUserForm"
              :rules="formRules"
              label-width="120px"
              class="config-form"
            >
              <el-form-item label="" prop="avatar">
                <el-upload
                  class="avatar-uploader"
                  :http-request="customUpload"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                >
                  <el-avatar
                    :size="64"
                    class="avatar"
                    :src="virtUserForm.avatar"
                  >
                    <el-icon><User /></el-icon>
                  </el-avatar>
                  <div class="avatar-hover-mask">
                    <el-icon><Upload /></el-icon>
                  </div>
                </el-upload>
              </el-form-item>

              <el-form-item label="用户名" prop="username" required>
                <el-input
                  v-model="virtUserForm.username"
                  placeholder="请输入虚拟用户名"
                />
              </el-form-item>

              <el-form-item label="昵称" prop="nickname">
                <el-input
                  v-model="virtUserForm.nickname"
                  placeholder="请输入虚拟用户昵称"
                />
              </el-form-item>

              <el-form-item label="描述信息" prop="description">
                <el-input
                  type="textarea"
                  v-model="virtUserForm.description"
                  placeholder="请输入虚拟人描述信息"
                  :rows="3"
                />
              </el-form-item>
              <el-form-item label="绑定能力">
                <el-select 
                  v-model="virtUserForm.capability"
                  placeholder="请选择能力类型"
                  class="capability-select"
                >
                  <el-option label="简单助手" value="assistant" />
                  <el-option label="工作流" value="workflow" />
                </el-select>
              </el-form-item>

              <!-- 当选择简单助手时显示 -->
              <el-form-item v-if="virtUserForm.capability === 'assistant'" label="">
                <el-select 
                  v-model="virtUserForm.selectedArtifact"
                  placeholder="请选择助手"
                  class="capability-sub-select"
                >
                  <el-option
                    v-for="assistant in llmAssistants"
                    :key="assistant.urn"
                    :label="assistant.name"
                    :value="assistant.urn"
                  />
                </el-select>
              </el-form-item>

              <!-- 当选择工作流时显示 -->
              <el-form-item v-if="virtUserForm.capability === 'workflow'" label="">
                <el-select
                  v-model="virtUserForm.selectedArtifact"
                  placeholder="请选择工作流"
                  class="capability-sub-select"
                >
                  <el-option
                    v-for="workflow in workflowOptions"
                    :key="workflow.value"
                    :label="workflow.label"
                    :value="workflow.value"
                  />
                </el-select>
              </el-form-item>

              <!-- 添加保存按钮 -->
              <el-form-item>
                <el-button 
                  type="primary" 
                  @click="handleSaveVirtUser"
                  :loading="isSaving"
                >
                  保存
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>

        <!-- Right Column -->
        <!-- <div class="right-column">
          <div class="preview-section">
            <div class="preview-header">
              <span>调试与预览</span>
              <div class="model-selector">
                <span>添加模型(2/4)</span>
              </div>
            </div>
            <div class="preview-content">
              <div class="preview-item">
                <span>#1</span>
                <el-select placeholder="选择您的模型"></el-select>
                <el-button class="more-options">...</el-button>
              </div>
              <div class="preview-item">
                <span>#2</span>
                <el-select placeholder="选择您的模型"></el-select>
                <el-button class="more-options">...</el-button>
              </div>
            </div>
            <div class="chat-area">
              <div class="chat-label">和机器人聊天</div>
              <div class="status-bar">
                <span class="status-icon">功能已开启</span>
                <el-button type="text">管理 ></el-button>
              </div>
            </div>
          </div>
        </div> -->
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted,computed,watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter,useRoute } from 'vue-router'
import { UpdateLLMAssistantRequest,CreateLLMAssistantRequest,GetLLMAssistantRequest, LLMAssistant, LLMModel, GeneratePromptRequest} from "@/types/proto/api/v1/llm_service";
import {GetAssistant, ListModels, GeneratePrompt,UpdateAssistant, CreateAssistant, ListAssistants} from "@/api/llm"
import { useUserStore } from '@/store/user'
import SideMenu from '@/components/SideMenu.vue'
import { Plus, Upload } from '@element-plus/icons-vue'
import {User, GetUserRequest, ListUsersRequest, ListUsersResponse, CreateUserRequest, UpdateUserRequest, GetVirtUserRequest,SetVirtUserRequest,SetVirtUserResponse} from '@/types/proto/api/v1/user_service'
import {CreateVirt, GetUser, UpdateVirt,GetVirtUserAbility,SetVirtUserAbility} from '@/api/user'
import defaultAvatar from '@/assets/icon/default-avatar.png'
import {Role} from '@/types/proto/common/common'
import {CreateResourceRequest} from '@/types/proto/api/v1/resource_service'
import { getBaseUrl }from '@/config'
import { CreateResource } from '@/api/resource'

const isSaving = ref(false)
const virtUser = ref<User | null>(null)
const llmAssistants = ref<LLMAssistant[]>([])
const userStore = useUserStore()
const router = useRouter()
const isGenerating = ref(false)

const workflowOptions = ref([
  { label: '工作流1', value: 'workflow1' },
  { label: '工作流2', value: 'workflow2' },
])

interface VirtUserForm {
  description: string
  currentUser: User|null,
  username: string
  nickname: string
  capabilities: string[]
  selectedArtifact: string
  avatar: string
  avatarCache: string
  capability: string
}

const virtUserForm = ref<VirtUserForm>({
  description: '',
  currentUser:null,
  username: '',
  nickname: '',
  avatar: "",
  avatarCache: "",
  capabilities: [],
  selectedArtifact: '',
  capability: '',
})

const formRules = {
  name: [
    { required: true, message: '请输入助手名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  modelType: [
    { required: true, message: '请选择模型', trigger: 'change' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
}

const formRef = ref()

const handleSaveVirtUser = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    isSaving.value = true
    let userUrn = ""
    if (virtUserForm.value.currentUser) {
        let u = {...virtUserForm.value.currentUser}
        let updateMask = []
        if (u.username !== virtUserForm.value.username) {
            u.username = virtUserForm.value.username
            updateMask.push("username")
        }

        if (u.nickname !== virtUserForm.value.nickname) {
            u.nickname = virtUserForm.value.nickname
            updateMask.push("nickname")
        }

        if (u.avatar !== virtUserForm.value.avatarCache) {
            u.avatar = virtUserForm.value.avatarCache
            updateMask.push("avatar")
        }

        if (u.description !== virtUserForm.value.description) {
            u.description = virtUserForm.value.description
            updateMask.push("description")

        }


        let req = {user:u, updateMask:updateMask} as UpdateUserRequest
        let res = await UpdateVirt(req)
        userUrn = res.urn
        console.log("update result:", res)
    } else {
        let req = {role:Role.AI_ASSISTANT, 
          username:virtUserForm.value.username, 
          email:virtUserForm.value.username, 
          nickname:virtUserForm.value.nickname, 
          description:virtUserForm.value.description, 
          tenantUrn:userStore.tenantUrn} as CreateUserRequest
        if (virtUserForm.value.avatar !== defaultAvatar) {
          req.avatar = virtUserForm.value.avatar
        }
        let res = await CreateVirt(req)
        userUrn = res.urn
        console.log("create result:", res)
    }

    let req2 = {urn:userUrn, artifactUrn:virtUserForm.value.selectedArtifact} as SetVirtUserRequest
    let res2 = await SetVirtUserAbility(req2)
    ElMessage.success('保存成功')
  } catch (error) {
    if (error instanceof Error) {
      console.error('保存失败:', error)
      ElMessage.error('保存失败，请重试')
    }
  } finally {
    isSaving.value = false
  }
}

const route = useRoute()
const parseParamFromRoute = async () => {
    try {
        console.log("parse param")
        const userUrn = route.query.user
        let reload = true
        console.log("user urn:", userUrn)
        if (userUrn === null || userUrn === undefined) {
            virtUserForm.value.currentUser = null
            reload = false
        } else if (virtUser.value != null) {
            if (virtUser.value.urn === userUrn) {
                console.log("no need to reload")
                reload = false
            }
        }

        const pageToken = { limit: 1000, offset: 0 }
        const filter = ""
        let listRes = await ListAssistants({ pageSize: 1000, pageToken, filter: filter })
        llmAssistants.value = listRes.assistants

        if (reload) {
            let req = {urn:userUrn} as GetUserRequest
            let res = await GetUser(req)
            virtUser.value = res
        }

        console.log("virtUser1:", virtUser.value)
        virtUserForm.value.avatar = defaultAvatar
        console.log("virtUser2:", virtUser.value)

        if (virtUser.value) {
            virtUserForm.value = {
                username: virtUser.value.username || '',
                nickname: virtUser.value.nickname || '',
                description: virtUser.value.description || '',
                avatar: virtUser.value.avatar || defaultAvatar,
                avatarCache: virtUser.value.avatar || defaultAvatar,
                capabilities:  [],
                selectedArtifact: '',
                capability: '',
                currentUser:virtUser.value
            }

            let req2 = {urn:userUrn} as GetVirtUserRequest
            let ability = await GetVirtUserAbility(req2)
            let r = ability.artifactUrn
            console.log("ability:", r)
            if (r != "" && r.startsWith("assistant")) {
                let req3 = {urn:r} as GetLLMAssistantRequest
                let res3 = await GetAssistant(req3)
                console.log("res3:", res3)
                // 设置默认能力类型为 assistant
                virtUserForm.value.capability = 'assistant'
                virtUserForm.value.selectedArtifact = r
            }
        }

    } catch (error) {
        console.error('Error parsing virtman from route:', error)
    }
}

const customUpload = async (options: any) => {
  try {
    const file = options.file
    // 先创建本地预览
    const localUrl = URL.createObjectURL(file)
    virtUserForm.value.avatar = localUrl // 立即更新预览

    let req = {filename:file.name, type:file.type} as CreateResourceRequest
    req.content = new Uint8Array(await file.arrayBuffer())
    let res = await CreateResource(req)
    // /file/{urn=resources/*}/{filename}
    virtUserForm.value.avatarCache = getBaseUrl() + "/file/"+res.urn+"/"+file.name


    // const avatar = await new Promise<string>((resolve, reject) => {
    //   const reader = new FileReader();
    //   reader.onload = () => resolve(reader.result as string);
    //   reader.onerror = reject;
    //   reader.readAsDataURL(file);
    // });
    // userInfo.avatarCache = avatar
  
  } catch (error) {
    console.error("custom upload error:", error)
    ElMessage.error('上传失败')
    options.onError(error)
  }
}

// const customUpload = async (options: any) => {
//   try {
//     const file = options.file
//     const localUrl = URL.createObjectURL(file)
//     virtUserForm.value.avatar = localUrl // Update preview immediately
//     const avatarDataUrl = await new Promise<string>((resolve, reject) => {
//       const reader = new FileReader()
//       reader.onload = () => resolve(reader.result as string)
//       reader.onerror = reject
//       reader.readAsDataURL(file)
//     })
//     virtUserForm.value.avatarCache = avatarDataUrl
//   } catch (error) {
//     console.error("custom upload error:", error)
//     ElMessage.error('上传失败')
//     options.onError(error)
//   }
// }

const handleAvatarSuccess = (res: any) => {
  ElMessage.success('头像已准备好，请点击保存按钮保存修改')
}

const beforeAvatarUpload = (file: File) => {
  const isValidFormat = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isValidFormat) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
  }
  return isValidFormat && isLt2M
}

onMounted(() => {
  console.log("assistant config on mounted")
  if (!userStore.token) {
    ElMessage.warning('请先登录')
    router.push('/signin')
    return
  }
  
  parseParamFromRoute()
})
</script>

<style scoped lang="scss">
.home-container {
  display: flex;
  max-width: 1440px;
  margin: 0 auto;
  padding: 0;
}

.main-content {
  flex: 1;
  margin-left: 100px;
  padding: 20px 40px;
}

.content-layout {
  display: flex;
  gap: 24px;
  height: 100%;
}

.left-column {
  flex: 1;
  max-width: 600px;
}

.right-column {
  flex: 1;
  min-width: 400px;
}

.prompt-config {
  padding: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.prompt-section, .variables-section, .context-section, .preview-section {
  margin-bottom: 20px;
  background: #fff;
  padding: 15px;
  border-radius: 8px;
}

.char-count {
  text-align: right;
  color: #999;
  font-size: 12px;
}

.variable-hint, .context-hint {
  color: #666;
  font-size: 14px;
  padding: 10px 0;
}

.preview-section {
  height: 100%;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.preview-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.preview-item {
  display: flex;
  align-items: center;
  gap: 12px;
  background: #f5f7fa;
  padding: 15px;
  border-radius: 8px;

  .el-select {
    flex: 1;
  }

  .more-options {
    padding: 0 8px;
  }
}

.chat-area {
  margin-top: auto;
  padding-top: 20px;
  border-top: 1px solid #eee;

  .chat-label {
    font-size: 14px;
    color: #333;
    margin-bottom: 12px;
  }

  .status-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #f5f7fa;
    padding: 12px;
    border-radius: 6px;

    .status-icon {
      color: #666;
      font-size: 14px;
    }
  }
}

.assistant-info-section {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 20px;

  .config-form {
    max-width: 800px;

    :deep(.el-form-item) {
      margin-bottom: 24px;

      .el-form-item__label {
        font-weight: 500;
        color: #333;
        line-height: 32px;
      }

      .el-form-item__content {
        display: flex;
        align-items: center;
      }
    }

    .model-select {
      width: 100%;
    }

    .el-input, .el-select {
      max-width: 500px;
    }
  }

  .save-section {
    margin-top: 32px;
    border-top: 1px solid #eee;
    padding-top: 24px;
    display: flex;
    justify-content: flex-end;
  }
}

.prompt-section {
  .prompt-footer {
    margin-top: 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .char-count {
      color: #909399;
    }
  }
}

.avatar-uploader {
  position: relative;
  display: inline-block;
  cursor: pointer;
}

.avatar-hover-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  border-radius: 50%;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-uploader:hover .avatar-hover-mask {
  opacity: 1;
}

.avatar {
  width: 100px;
  height: 100px;
  background-color: hsl(210, 25%, 95%);
  font-size: 32px;
}

.assistant-select {
  width: 100%;
}

.capability-select {
  width: 100%;
  max-width: 500px;
}

.capability-sub-select {
  width: 100%;
  max-width: 500px;
}

@media screen and (max-width: 1440px) {
  .home-container {
    max-width: 100%;
  }
  
  .main-content {
    margin-left: 220px;
  }
}

@media screen and (max-width: 1200px) {
  .main-content {
    margin-left: 200px;
  }
}
</style>
